package com.zhangxu.microservice.common.utils;

/**
 * 更加优雅完善的脱敏工具类
 * 支持手机号、邮箱、姓名、地址、银行卡号等脱敏
 */
public class DesensitizationUtils {

    /**
     * 通用脱敏方法
     *
     * @param str          原始字符串
     * @param prefixLength 前缀保留长度
     * @param suffixLength 后缀保留长度
     * @param maskChar     脱敏字符
     * @return 脱敏后字符串
     */
    private static String desensitize(String str, int prefixLength, int suffixLength, char maskChar) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        int strLength = str.length();
        if (prefixLength + suffixLength >= strLength) {
            return str; // 不足以脱敏
        }
        StringBuilder sb = new StringBuilder();
        sb.append(str, 0, prefixLength);
        for (int i = 0; i < strLength - prefixLength - suffixLength; i++) {
            sb.append(maskChar);
        }
        sb.append(str.substring(strLength - suffixLength));
        return sb.toString();
    }

    /**
     * 姓名脱敏（保留首字符）
     * 张三 -> 张*
     * 李小龙 -> 李**
     */
    public static String desensitizeName(String name) {
        if (name == null || name.isEmpty()) {
            return name;
        }
        return name.charAt(0) + "*".repeat(Math.max(1, name.length() - 1));
    }

    /**
     * 手机号脱敏（保留前三后四）
     * 18812345678 -> 188****5678
     */
    public static String desensitizePhone(String phone) {
        return desensitize(phone, 3, 4, '*');
    }

    /**
     * 邮箱脱敏
     * test@gmail.com -> t***@gmail.com
     */
    public static String desensitizeEmail(String email) {
        if (email == null || email.isEmpty() || !email.contains("@")) {
            return email;
        }
        String[] parts = email.split("@", 2);
        String localPart = parts[0];
        String domainPart = parts[1];

        String maskedLocal = desensitize(localPart, 1, 0, '*');
        return maskedLocal + "@" + domainPart;
    }

    /**
     * 地址脱敏（保留前6位）
     * 上海市浦东新区张江高科 -> 上海市浦东新区****
     */
    public static String desensitizeAddress(String address) {
        if (address == null || address.isEmpty()) {
            return address;
        }
        int keep = Math.min(6, address.length());
        return desensitize(address, keep, 0, '*');
    }

    /**
     * 银行卡号脱敏（保留前6后4）
     * 6222021234567890 -> 622202******7890
     */
    public static String desensitizeBankCard(String cardNo) {
        return desensitize(cardNo, 6, 4, '*');
    }

    /**
     * 身份证脱敏（保留前3后4）
     * 110105199001012345 -> 110***********2345
     */
    public static String desensitizeIdCard(String idCard) {
        return desensitize(idCard, 3, 4, '*');
    }
}
